package com.sqlparser.core.executor.impl;

import com.sqlparser.core.executor.Executor;
import com.sqlparser.core.parser.ast.*;
import com.sqlparser.storage.Storage;
import com.sqlparser.common.exception.SQLParserException;

import java.util.List;
import java.util.Map;
import java.util.Collections;

/**
 * 简单的SQL执行引擎实现
 */
public class SimpleExecutor implements Executor {
    private final Storage storage;
    
    public SimpleExecutor(Storage storage) {
        this.storage = storage;
    }
    
    @Override
    public List<Map<String, Object>> execute(SQLStatement statement) {
        if (statement instanceof SelectStatement) {
            return executeSelect((SelectStatement) statement);
        } else if (statement instanceof DeleteStatement) {
            return executeDelete((DeleteStatement) statement);
        }
        throw new SQLParserException("Unsupported statement type: " + statement.getClass().getName());
    }
    
    private List<Map<String, Object>> executeSelect(SelectStatement select) {
        String tableName = select.getTableName();
        List<String> columns = select.getColumns();
        String condition = buildConditionString(select.getWhereClause());
        
        return storage.query(tableName, columns, condition);
    }
    
    private List<Map<String, Object>> executeDelete(DeleteStatement delete) {
        String tableName = delete.getTableName();
        String condition = buildConditionString(delete.getWhereClause());
        
        int affectedRows = storage.delete(tableName, condition);
        
        // 返回受影响的行数作为结果
        return Collections.singletonList(
            Collections.singletonMap("affected_rows", affectedRows)
        );
    }
    
    private String buildConditionString(WhereClause whereClause) {
        if (whereClause == null) {
            return null;
        }
        
        return String.format("%s %s %s",
            whereClause.getColumn(),
            whereClause.getOperator(),
            whereClause.getValue());
    }
} 